<template>
    <div class="container">
        <!-- <h1>视频分析记录与对比</h1> -->

        <!-- 记录列表 -->
        <el-card>
            <el-button type="primary" icon="el-icon-search">搜索</el-button>
            <el-button type="primary" @click="$router.go(-1)" style="margin-bottom: 20px">
                返回视频检测
            </el-button>
            <div class="task-list">
                <el-table v-loading="loading" :data="allTasks" style="width: 100%">
                    <!-- 折叠面板 type="expand"-->
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <VideoCompare :original-src="scope.row.originalVideoUrl"
                                :processed-src="scope.row.processedVideoUrl" />
                            <VideoAnalysis :taskId="scope.row.taskId" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="taskId" label="任务ID" width="300">
                    </el-table-column>
                    <el-table-column label="状态" width="120">
                        <template slot-scope="scope">
                            <el-tag :type="statusType(scope.row.status)">
                                {{ scope.row.status }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="filename" label="文件名" width="200"></el-table-column>
                    <el-table-column prop="progress" label="处理进度" width="200">
                        <template slot-scope="scope">
                            <el-progress :percentage="scope.row.progress"></el-progress>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button v-if="scope.row.status === 'completed'" type="success" icon="el-icon-download"
                                @click="downloadResult(scope.row)">下载结果</el-button>
                            <el-button v-if="scope.row.status === 'completed'"
                                @click="showCompareView(scope.row)">对比展示</el-button>
                            <el-button v-if="scope.row.status === 'completed'" type="danger" icon="el-icon-warning"
                                @click="showAnalysisView(scope.row.taskId)">查看详情</el-button>
                            <el-button v-if="scope.row.status === 'failed'" type="danger" icon="el-icon-warning"
                                @click="showError(scope.row)">查看错误</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 在任务列表后添加对比展示区域 -->
            <div class="compare-section" v-if="isShowCompare">
                <VideoCompare :original-src="originalVideoUrl" :processed-src="processedVideoUrl" />
            </div>

            <!-- 数据分析展示 -->
            <div v-if="isShowAnalysis">
                <VideoAnalysis :taskId="taskId" />
            </div>

            <!-- 错误对话框 -->
            <el-dialog title="错误详情" :visible.sync="errorDialogVisible">
                <div class="error-content">
                    <pre>{{ currentError }}</pre>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import VideoCompare from './components/VideoCompare.vue'
import VideoAnalysis from './VideoAnalysis.vue';
import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:5000'

export default {
    components: { VideoCompare, VideoAnalysis },
    data() {
        return {
            loading: true,
            allTasks: [],
            selectedTask: null,
            originalVideoUrl: '',
            processedVideoUrl: '',
            selectedFile: null,
            uploading: false,
            uploadProgress: 0,
            tasks: [],
            errorDialogVisible: false,
            currentError: '',
            pollIntervals: {},
            isShowCompare: false,
            originalVideoUrl: '',
            processedVideoUrl: '',
            isShowAnalysis: false,
            taskId: '',
        }
    },
    methods: {
        // showCompare(task) {
        //     this.selectedTask = task
        //     this.originalVideoUrl = `http://localhost:5000/original_video/${task.taskId}`
        //     this.processedVideoUrl = `http://localhost:5000/processed_video/${task.taskId}`
        // },
        showAnalysisView(taskId) {
            this.isShowAnalysis = true;
            this.taskId = taskId;
        },
        showCompareView(task) {
            console.log(task)
            this.originalVideoUrl = `http://localhost:5000/original_video/${task.taskId}`
            this.processedVideoUrl = `http://localhost:5000/processed_video/${task.taskId}`
            // this.processedVideoUrl = `http://localhost:9090/admin/system/file/204da308baca41cfab6224072e1f27af.mp4`
            this.isShowCompare = true
        },
        triggerFileSelect() {
            this.$refs.fileInput.click()
        },
        handleFileSelect(e) {
            const files = e.target.files
            if (files.length > 0) {
                this.selectedFile = files[0]
            }
        },
        async startUpload() {
            if (!this.selectedFile) return

            this.uploading = true
            const formData = new FormData()
            formData.append('file', this.selectedFile)

            try {
                const response = await axios.post('/upload', formData, {
                    onUploadProgress: progressEvent => {
                        this.uploadProgress = Math.round(
                            (progressEvent.loaded * 100) / progressEvent.total
                        )
                    }
                })

                const taskData = {
                    taskId: response.data.task_id,
                    filename: this.selectedFile.name,
                    status: 'pending',
                    downloadUrl: response.data.download_url
                }

                this.tasks.unshift(taskData)
                this.saveTasks()
                this.startPolling(taskData.taskId)

                this.$message.success('文件上传成功，开始分析处理')
            } catch (error) {
                this.$message.error(`上传失败: ${error.message}`)
            } finally {
                this.uploading = false
                this.uploadProgress = 0
                this.selectedFile = null
            }
        },
        startPolling(taskId) {
            if (this.pollIntervals[taskId]) return

            this.pollIntervals[taskId] = setInterval(async () => {
                try {
                    const response = await axios.get(`/status/${taskId}`)
                    const task = this.tasks.find(t => t.taskId === taskId)
                    console.log(response.data)
                    if (task) {
                        task.status = response.data.status

                        if (response.data.status === 'processing') {
                            task.progress = response.data.progress
                            // const progress = (data.current / data.total) * 100
                            // updateProgressBar(progress) // 更新进度条
                            // this.percentage = response.data.progress
                        }

                        if (response.data.status === 'completed') {
                            clearInterval(this.pollIntervals[taskId])
                            task.progress = response.data.progress
                            delete this.pollIntervals[taskId]
                            this.$message.success('分析处理完成')
                        }

                        if (response.data.status === 'failed') {
                            clearInterval(this.pollIntervals[taskId])
                            delete this.pollIntervals[taskId]
                            task.error = response.data.error
                            this.$message.error('处理失败')
                        }

                        this.saveTasks()
                    }
                } catch (error) {
                    console.error('轮询错误:', error)
                }
            }, 3000) // 每3秒轮询一次
        },
        statusType(status) {
            switch (status) {
                case 'completed': return 'success'
                case 'failed': return 'danger'
                default: return 'info'
            }
        },
        downloadResult(task) {
            console.log(task)
            window.open(`http://localhost:5000${task.downloadUrl}`, "_blank")
        },
        showError(task) {
            this.currentError = task.error || '未知错误'
            this.errorDialogVisible = true
        },
        saveTasks() {
            localStorage.setItem('videoTasks', JSON.stringify(this.tasks))
        }
    },
    mounted() {
        // 通过路由参数直接打开对比
        // if (this.$route.query.taskId) {
        //     const task = this.allTasks.find(
        //         t => t.taskId === this.$route.query.taskId
        //     )
        //     if (task) this.showCompare(task)
        // }
        // 初始化时加载本地存储的任务
        const savedTasks = localStorage.getItem('videoTasks')
        if (savedTasks) {
            this.allTasks = JSON.parse(savedTasks)
            this.loading = false
            // 恢复轮询
            this.allTasks.forEach(task => {
                if (!['completed', 'failed'].includes(task.status)) {
                    this.startPolling(task.taskId)
                }
            })
        }
    }

}
</script>

<style scoped>
.container {
    text-align: center;
    margin: 20px auto;
    padding: 20px;
}
</style>